package com.liliudong.template.biz.service.sys.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.template.biz.mapper.sys.SysRoleMenuMapper;
import com.liliudong.template.biz.service.sys.SysRoleMenuService;
import com.liliudong.template.common.entity.sys.SysRoleMenu;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * sys角色菜单服务impl
 *
 * @author ldli5
 * @date 2024/06/20
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

	@Override
	public void saveBatchWithRoleId(Long roleId, List<Long> menuIds) {
		List<SysRoleMenu> sysRoleMenuList = menuIds.stream()
				.map(menuId -> {
					SysRoleMenu sysRoleMenu = new SysRoleMenu();
					sysRoleMenu.setRoleId(roleId);
					sysRoleMenu.setMenuId(menuId);
					return sysRoleMenu;
				})
				.collect(Collectors.toList());
		this.saveBatch(sysRoleMenuList);
	}

	@Override
	public void removeByRoleId(Long roleId) {
		this.remove(lambdaQuery().eq(SysRoleMenu::getRoleId, roleId).getWrapper());
	}

	@Override
	@Transactional
	public void updateBatchWithRoleId(Long roleId, List<Long> menuIds) {
		this.removeByRoleId(roleId);
		this.saveBatchWithRoleId(roleId, menuIds);
	}

	@Override
	public long countByMenuId(Long menuId) {
		return count(lambdaQuery().eq(SysRoleMenu::getMenuId, menuId).getWrapper());
	}

	@Override
	public Set<Long> listMenuIdsByRoleId(Long roleId) {
		return list(
				lambdaQuery()
						.select(SysRoleMenu::getMenuId)
						.eq(SysRoleMenu::getRoleId, roleId)
						.getWrapper()
		).stream()
				.map(SysRoleMenu::getMenuId)
				.collect(Collectors.toSet());
	}

	@Override
	public Set<Long> listMenuIds() {
		return list(
				lambdaQuery()
						.select(SysRoleMenu::getMenuId)
		).stream()
				.map(SysRoleMenu::getMenuId)
				.collect(Collectors.toSet());
	}
}
